import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:infinite_list/bloc/post_bloc.dart';

import 'models/post.dart';

class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onTransition(Bloc bloc, Transition transition) {
    print(transition);
    super.onTransition(bloc, transition);
  }
}

void main() {
  BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        
        primarySwatch: Colors.blue,
        
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('Infinite List'),),
        body: BlocProvider<PostBloc>(
          create: (context) => PostBloc(httpClient: http.Client())..add(Fetch()),
          child: HomePage(),
        ),
      )
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _scrollController = ScrollController();
  final _scrollThreshold = 200;
  PostBloc _postBloc;

  @override
  void initState() { 
    super.initState();
    _scrollController.addListener(_onScroll);
    _postBloc = BlocProvider.of<PostBloc>(context);
  }

  void _onScroll(){
    final maxScroll = _scrollController.position.maxScrollExtent;
    final currentScroll = _scrollController.position.pixels;
    if(_scrollThreshold >= maxScroll - currentScroll)
      _postBloc.add(Fetch());
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
       child: BlocBuilder<PostBloc, PostState>(
         builder: (context, state) {
           if(state is PostUninitialized){
             return Center(child: CircularProgressIndicator(),);
           }else if(state is PostError){
             return Center(child: Text('Fetch Error!',style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold,)),);
           }else if(state is PostLoaded){
             if(state.posts.isEmpty){
               return Center(child: Text('Fetch Empty!',style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold,),),);
             }else{
               return ListView.builder(
                 itemBuilder: (context,index) {
                   return index >= state.posts.length
                   ? ButtonLoader()
                   :PostWidget(post: state.posts[index],);
                 },
                 itemCount: state.hasReachedMax
                 ?state.posts.length
                 :state.posts.length + 1,
                 controller: _scrollController,
               );
             }
           }
         },
       ),
    );
  }
}

class ButtonLoader extends StatelessWidget {
  const ButtonLoader({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Container(
        alignment: Alignment.center,
        child: Center(
          child: SizedBox(
            child: CircularProgressIndicator(strokeWidth: 1.5,),
            height: 33,
            width: 33,
          ),
        ),
      ),
    );
  }
}

class PostWidget extends StatelessWidget {
  const PostWidget({Key key,@required this.post}) :super(key:key);

  final Post post;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Text('${post.id}',style: TextStyle(fontSize: 10),),
      title: Text(post.title),
      isThreeLine: true,
      subtitle: Text(post.body),
      dense: true,
    );
  }
}